package com.example.tongyao.system.controller;


import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.example.tongyao.common.SuperController;
import com.example.tongyao.system.entity.SysFreeAuth;
import com.example.tongyao.system.entity.SysUser;
import com.example.tongyao.system.message.SystemMessage;
import com.example.tongyao.system.service.ISysFreeAuthService;
import com.example.tongyao.utils.*;
import com.example.tongyao.utils.token.UserUtils;
import com.example.tongyao.utils.tongyao.TyUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 权限路径表 前端控制器
 * </p>
 *
 * @author tongyao
 * @since 2021-08-18
 */
@RestController
@Api(tags = "系统_免认证接口前端控制器")
@RequestMapping("/system/sys-free-auth")
public class SysFreeAuthController extends SuperController {

    @Resource
    private ISysFreeAuthService iSysFreeAuthService;

    /**
     * 分页查询所有配置
     * @return
     */
    @ApiOperation(
            value = "查询免认证接口",
            notes = "分页查询免认证接口路径",
            httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pathAddress",value = "免认证接口路径"),
            @ApiImplicitParam(name = "pageNo",value = "当前页数",defaultValue = "1"),
            @ApiImplicitParam(name = "pageSize",value = "显示条数",defaultValue = "10"),
            @ApiImplicitParam(name = "sortBy",value = "排序字段（多个以英文逗号拼接）",defaultValue = "create_time"),
            @ApiImplicitParam(name = "order",value = "排序类型",defaultValue = "asc")
    })
    @GetMapping(value = "/page" , produces = {MediaType.APPLICATION_JSON_VALUE})
    public DataResult page(
            @RequestParam(required = false) String pathAddress,
            @RequestParam(defaultValue = "1") int pageNo,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(defaultValue = "sfa.create_time") String sortBy,
            @RequestParam(defaultValue = "asc") String order) {

        PageUtil<SysFreeAuth> page = new PageUtil<>(pageNo,pageSize,sortBy,order);
        Map<String, Object> params = TyUtils.toObjectMap(page);
        params.put("pathAddress",pathAddress);


        List<SysFreeAuth> list = iSysFreeAuthService.freeAuthPage(params);
        page.setPage(list,list.size(),pageNo);
        return DataResult.setSuccess(page);
    }


    @ApiOperation(
            value = "增加免认证接口",
            notes = "增加一个免认证接口",
            httpMethod = "POST")
    @PostMapping(value = "/save" , produces = {MediaType.APPLICATION_JSON_VALUE})
    public DataResult save(@Valid @RequestBody(required = true) SysFreeAuth sysFreeAuth) {

        codeExist(sysFreeAuth.getPathAddress());
        SysUser user = (SysUser) UserUtils.getUserInfo();

        sysFreeAuth.setPathEnabled(true);
        sysFreeAuth.setDelFlag(1);

        sysFreeAuth.setCreateBy(user.getUserId());
        sysFreeAuth.setCreateTime(DateUtils.getDateTime());

        reuslt = iSysFreeAuthService.save(sysFreeAuth);
        if(!reuslt){
            throw new RuntimeException(SystemMessage.freeAuthPath+SystemMessage.add+SystemMessage.fail+SystemMessage.a);
        }
        return DataResult.setSuccess(null);
    }

    @ApiOperation(
            value = "编辑免认证接口",
            notes = "编辑一个免认证接口，需根据freeAuthId字段。",
            httpMethod = "PUT")
    @PutMapping(value = "/edit" , produces = {MediaType.APPLICATION_JSON_VALUE})
    public DataResult edit(@Valid @RequestBody SysFreeAuth sysFreeAuth){

        SysUser user = (SysUser) UserUtils.getUserInfo();

        LambdaUpdateWrapper<SysFreeAuth> sysFreeAuthLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        if(StringUtils.isNotBlank(sysFreeAuth.getPathAddress())){
            codeExist(sysFreeAuth.getPathAddress());
            sysFreeAuthLambdaUpdateWrapper.set(SysFreeAuth::getPathAddress,sysFreeAuth.getPathAddress());
        }
        if(StringUtils.isNotBlank(sysFreeAuth.getPathDesc())){
            sysFreeAuthLambdaUpdateWrapper.set(SysFreeAuth::getPathDesc,sysFreeAuth.getPathDesc());
        }
        if(StringUtils.isNotBlank(sysFreeAuth.getPathType())){
            sysFreeAuthLambdaUpdateWrapper.set(SysFreeAuth::getPathType,sysFreeAuth.getPathType());
        }
        if(StringUtils.isNotNull(sysFreeAuth.getSort())){
            sysFreeAuthLambdaUpdateWrapper.set(SysFreeAuth::getSort,sysFreeAuth.getSort());
        }


        sysFreeAuthLambdaUpdateWrapper.set(SysFreeAuth::getModifyBy,user.getUserId());
        sysFreeAuthLambdaUpdateWrapper.set(SysFreeAuth::getModifyTime,DateUtils.getDateTime());

        sysFreeAuthLambdaUpdateWrapper.eq(SysFreeAuth::getFreeAuthId,sysFreeAuth.getFreeAuthId());

        reuslt = iSysFreeAuthService.update(sysFreeAuthLambdaUpdateWrapper);
        if(!reuslt){
            throw new RuntimeException(
                    SystemMessage.freeAuthPath+
                            SystemMessage.update+
                            SystemMessage.fail+
                            SystemMessage.a);
        }
        return DataResult.setSuccess(null);
    }

    @ApiOperation(
            value = "删除免认证接口",
            notes = "删除一个或多个免认证接口",
            httpMethod = "DELETE")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "freeAuthId",value = "免认证接口编号，多个以英文逗号拼接",required = true),
    })
    @DeleteMapping(value = "/delete" , produces = {MediaType.APPLICATION_JSON_VALUE})
    public DataResult delete(@RequestParam String freeAuthId){

        List freeAuthIds = Arrays.asList(freeAuthId.split(","));
        for (Object freeAuth: freeAuthIds) {

            //删除配置
            LambdaUpdateWrapper<SysFreeAuth> sysFreeAuthLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            sysFreeAuthLambdaUpdateWrapper
                    .set(SysFreeAuth::getDelFlag,"0")
                    .eq(SysFreeAuth::getFreeAuthId,freeAuth);
            reuslt = iSysFreeAuthService.update(sysFreeAuthLambdaUpdateWrapper);
            if(!reuslt){
                throw new RuntimeException(
                        SystemMessage.freeAuthPath+
                                SystemMessage.delete+
                                SystemMessage.fail+
                                SystemMessage.a
                );
            }

        }
        return DataResult.setSuccess(null);
    }


    @ApiOperation(
            value = "更改状态",
            notes = "更改免认证接口的启用禁用状态",
            httpMethod = "PUT")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "freeAuthId",value = "免认证接口编号",required = true),
            @ApiImplicitParam(name = "state",value = "配置状态（true为启用，false为禁用）",required = true)
    })
    @PutMapping(value = "/changeState" , produces = {MediaType.APPLICATION_JSON_VALUE})
    public DataResult changeState(
            @RequestParam String freeAuthId,
            @RequestParam boolean state
    ){

        LambdaUpdateWrapper<SysFreeAuth> sysFreeAuthLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        sysFreeAuthLambdaUpdateWrapper
                .set(SysFreeAuth::isPathEnabled,state)
                .eq(SysFreeAuth::getFreeAuthId,freeAuthId);
        reuslt = iSysFreeAuthService.update(sysFreeAuthLambdaUpdateWrapper);

        if(!reuslt){
            throw new RuntimeException(
                    SystemMessage.freeAuthPath +
                            SystemMessage.state+
                            SystemMessage.update +
                            SystemMessage.fail +
                            SystemMessage.a
            );
        }

        return DataResult.setSuccess(null);
    }

    /**
     * 判断免认证接口是否存在
     * @param code
     * @return
     */
    public void codeExist(String code){
        int count = commonService.getCount("sys_free_auth","path_address = '"+code+"' and del_flag = 1");
        if(count > 0){
            throw new RuntimeException(code+" 免认证接口已存在！");
        }
    }
}
